// https://www.lintcode.com/problem/find-minimum-in-rotated-sorted-array/description?_from=ladder&&fromId=6
// Suppose a sorted array is rotated at some pivot unknown to you beforehand.

// (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

// Find the minimum element.

// Example
// Given [4, 5, 6, 7, 0, 1, 2] return 0

// Notice
// You may assume no duplicate exists in the array.


class Solution {
public:
    /**
     * @param nums: a rotated sorted array
     * @return: the minimum number in the array
     */
    // int findMin(vector<int> &nums) {
    //     int tmp = nums.size() - 1;
    //     while (tmp > 0 && nums[tmp - 1] < nums[tmp]) tmp--;
    //     return nums[tmp];
    // }
    
    // 二分法，找到第一个比最后一个数小的数
    // 法一：nums.back()作为target
    int findMin(vector<int> &nums) {
        int target = nums.back();
        int low = 0;
        int high = nums.size() - 1;
        while (low + 1 < high)
        {
            int mid = (high - low) / 2 + low;
            if (nums[mid] >= target) low = mid;
            else high = mid;
        }
        if (nums[low] <= target) return nums[low];
        else return nums[high];
    }

    // 法二，只要比nums[end]小的第一个数，可以一直往前缩
     int findMin(vector<int> &nums) {
        int start = 0;
        int end = nums.size() - 1;
        while (start + 1 < end)
        {
            int mid = (end - start) / 2 + start;
            if (nums[mid] > nums[end]) start = mid;
            else end = mid;
        }
        if (nums[start] < nums[end]) return nums[start];
        return nums[end];
    }

    //个：二分法，找到比前一个数大的数
    int findMin(vector<int> &nums) {
        int start = 0;
        int end = nums.size() - 1;
        while (start + 1 < end)
        {
            int mid = (end - start) / 2 + start;
            if (mid && nums[mid] < nums[mid - 1]) return nums[mid];
            if (nums[mid] > nums.back()) start = mid;
            else end = mid;
        }
        if (nums[start] < nums[end]) return nums[start];
        return nums[end];
    }
};